#include <napi.h>
#include <windows.h>
#include <iostream>
Napi::Env g_env = nullptr;
Napi::FunctionReference globalFunctionRef;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
    DWORD processId;
    GetWindowThreadProcessId(hwnd, &processId);
    Napi::Function callback = globalFunctionRef.Value();
    if (processId == static_cast<DWORD>(lParam)) {
        wchar_t windowTitle[256];
        GetWindowTextW(hwnd, windowTitle, sizeof(windowTitle) / sizeof(wchar_t));
        if (wcslen(windowTitle) > 0) {
            Napi::String result = Napi::String::New(g_env, reinterpret_cast<const char16_t *>(windowTitle));
            callback.Call({ result });
            return FALSE; // 停止枚举
        }
    }

    return TRUE; // 继续枚举
}

Napi::Value GetActiveWindowInfo(const Napi::CallbackInfo &info) {
    Napi::Env env = info.Env();
    g_env = env;
    Napi::Object result = Napi::Object::New(env);
    Napi::Function callback = info[0].As<Napi::Function>();
    globalFunctionRef = Napi::Persistent(callback);
    HWND activeWindow = GetForegroundWindow(); // 获取当前激活窗口的句柄
    if (activeWindow) {
        DWORD activeProcessId;
        GetWindowThreadProcessId(activeWindow, &activeProcessId);
        EnumWindows(EnumWindowsProc, static_cast<LPARAM>(activeProcessId));
        return result;
    } else {
        result.Set("error", Napi::String::New(env, "error"));
        return result;
    }
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports.Set("getActiveWindowInfo", Napi::Function::New(env, GetActiveWindowInfo));
    return exports;
}

NODE_API_MODULE(windowInfoAddon, Init)